const { api } = require("../../utils/api.js");

// 发现页面
Page({
  data: {
    categories: [],
    selectedCategory: "",
    recipeList: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    showFilter: false,
    searchKeyword: "", // 搜索关键词
    isSearching: false, // 是否正在搜索
    searchHistory: [], // 搜索历史
    showSearchResult: false, // 是否显示搜索结果
    searchResultCache: {}, // 搜索结果缓存
  },

  // 搜索定时器，用于防抖
  searchTimer: null,

  onLoad() {
    // 检查登录状态
    const token = wx.getStorageSync("token");
    if (!token) {
      wx.showToast({
        title: "请先登录",
        icon: "none",
        duration: 2000,
        success: () => {
          setTimeout(() => {
            wx.redirectTo({
              url: "/pages/index/index",
            });
          }, 1000);
        },
      });
      return;
    }

    // 页面加载时的逻辑
    console.log("发现页面加载成功");
    this.getCategories();
    this.getRecipeList();

    // 获取搜索历史
    this.getSearchHistory();
  },

  onShow() {
    // 页面显示/切入前台时的逻辑
  },

  onHide() {
    // 页面隐藏/切入后台时的逻辑
    // 清除可能存在的定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
  },

  onUnload() {
    // 页面卸载时清除定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
  },

  onPullDownRefresh() {
    // 下拉刷新时的逻辑
    this.getRecipeList();
  },

  // 防抖函数
  debounce(func, delay = 300) {
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
    this.searchTimer = setTimeout(() => {
      func.apply(this);
    }, delay);
  },

  // 获取菜谱分类
  getCategories: function () {
    api
      .getRecipeCategories()
      .then((res) => {
        if (res.code === 200 && res.data) {
          this.setData({
            categories: res.data.list || [],
          });
        }
      })
      .catch((err) => {
        console.error("获取菜谱分类失败:", err);
        // 使用模拟数据
        this.setData({
          categories: [
            { id: "breakfast", name: "早餐" },
            { id: "lunch", name: "午餐" },
            { id: "dinner", name: "晚餐" },
            { id: "snack", name: "小食" },
            { id: "soup", name: "汤品" },
            { id: "vegetable", name: "素食" },
          ],
        });
      });
  },

  // 获取菜谱列表
  getRecipeList: function (isLoadMore = false) {
    if (this.data.loading || (!isLoadMore && !this.data.hasMore)) {
      return;
    }

    this.setData({ loading: true });

    const page = isLoadMore ? this.data.page + 1 : 1;
    console.log("获取菜谱列表, 当前分类:", this.data.selectedCategory); // 添加日志

    api
      .getRecipeList(page, this.data.pageSize, this.data.selectedCategory)
      .then((res) => {
        if (res.code === 200 && res.data) {
          let list = res.data.list || [];
          const total = res.data.total || 0;

          // 如果是"全部"分类，或者API返回的数据不足，使用模拟数据
          if (this.data.selectedCategory === "" || list.length < 3) {
            console.log("使用模拟数据充实列表");
            const mockData = this.getMockRecipes();

            // 根据当前分类过滤模拟数据
            let filteredMock = [];
            if (this.data.selectedCategory === "") {
              // 全部分类时，从每个分类中各取一部分数据
              const categories = [
                "breakfast",
                "lunch",
                "dinner",
                "snack",
                "soup",
                "vegetable",
              ];
              categories.forEach((category) => {
                // 每个分类取2个菜谱
                const categoryItems = mockData
                  .filter((item) => item.category === category)
                  .slice(0, 2);
                filteredMock = [...filteredMock, ...categoryItems];
              });

              // 将顶部三个菜谱添加到列表前面
              const topRecipes = [
                {
                  id: 1001,
                  title: "营养早餐三明治",
                  imageUrl: "/images/discovers/png/sanmingzhi.png",
                  description: "健康美味的三明治，含有丰富的蛋白质和维生素",
                  calories: 350,
                  cookingTime: "15分钟",
                  difficulty: "简单",
                  category: "breakfast",
                },
                {
                  id: 2001,
                  title: "清炒时蔬",
                  imageUrl: "/images/discovers/png/qingjiaoshishu.png",
                  description: "低脂健康的素食选择，富含膳食纤维",
                  calories: 200,
                  cookingTime: "20分钟",
                  difficulty: "简单",
                  category: "lunch",
                },
                {
                  id: 3001,
                  title: "养生排骨汤",
                  imageUrl: "/images/discovers/png/paigutang.png",
                  description: "滋补养生的排骨汤，营养丰富",
                  calories: 450,
                  cookingTime: "60分钟",
                  difficulty: "中等",
                  category: "dinner",
                },
              ];

              // 确保顶部菜谱不在列表中重复
              const recipeIds = new Set(filteredMock.map((item) => item.id));
              const uniqueTopRecipes = topRecipes.filter(
                (item) => !recipeIds.has(item.id)
              );
              filteredMock = [...uniqueTopRecipes, ...filteredMock];
            } else {
              filteredMock = mockData.filter(
                (item) => item.category === this.data.selectedCategory
              );
            }

            // 如果API返回了数据，则合并API数据和模拟数据
            if (list.length > 0) {
              // 获取API数据中的最后一个ID
              const lastId = list[list.length - 1].id;
              // 为模拟数据设置新的ID，避免ID冲突
              filteredMock = filteredMock.map((item, index) => ({
                ...item,
                id: lastId + index + 1,
              }));

              // 合并数据
              list = [...list, ...filteredMock];
            } else {
              // 如果API没有返回数据，直接使用模拟数据
              list = filteredMock;
            }
          }

          this.setData({
            recipeList: isLoadMore ? [...this.data.recipeList, ...list] : list,
            page: page,
            hasMore:
              this.data.pageSize * page < total ||
              list.length >= this.data.pageSize,
          });
        }
      })
      .catch((err) => {
        console.error("获取菜谱列表失败:", err);
        // 使用模拟数据
        const mockData = this.getMockRecipes();

        // 根据选中的分类过滤数据
        let filteredList = [];
        if (this.data.selectedCategory === "") {
          // 全部分类时，从每个分类中各取一部分数据
          const categories = [
            "breakfast",
            "lunch",
            "dinner",
            "snack",
            "soup",
            "vegetable",
          ];
          categories.forEach((category) => {
            // 每个分类取2个菜谱
            const categoryItems = mockData
              .filter((item) => item.category === category)
              .slice(0, 2);
            filteredList = [...filteredList, ...categoryItems];
          });
        } else {
          filteredList = mockData.filter(
            (item) => item.category === this.data.selectedCategory
          );
        }

        console.log("过滤后菜谱数量:", filteredList.length); // 添加日志

        this.setData({
          recipeList: isLoadMore
            ? [...this.data.recipeList, ...filteredList]
            : filteredList,
          page: page,
          hasMore: false,
        });

        console.log("设置后的菜谱列表:", this.data.recipeList); // 添加日志
      })
      .finally(() => {
        this.setData({ loading: false });
        wx.stopPullDownRefresh();
      });
  },

  // 获取模拟菜谱数据
  getMockRecipes: function () {
    return [
      // 早餐类
      {
        id: 1001,
        title: "营养早餐三明治",
        imageUrl: "/images/discovers/png/sanmingzhi.png",
        description: "健康美味的三明治，含有丰富的蛋白质和维生素",
        calories: 350,
        cookingTime: "15分钟",
        difficulty: "简单",
        category: "breakfast",
      },
      {
        id: 1002,
        title: "燕麦水果杯",
        imageUrl: "/images/discovers/png/yanmaishuiguozhou.png",
        description: "富含膳食纤维的燕麦，搭配新鲜水果，营养均衡",
        calories: 280,
        cookingTime: "10分钟",
        difficulty: "简单",
        category: "breakfast",
      },
      {
        id: 1003,
        title: "全麦吐司配牛油果",
        imageUrl: "/images/discovers/png/niuyouguo.png",
        description: "全麦面包搭配牛油果，健康又美味",
        calories: 320,
        cookingTime: "10分钟",
        difficulty: "简单",
        category: "breakfast",
      },
      {
        id: 1004,
        title: "蛋白质能量饼",
        imageUrl: "/images/discovers/png/danbaizhinengliangbing.png",
        description: "高蛋白饼干，运动前能量补充",
        calories: 270,
        cookingTime: "15分钟",
        difficulty: "中等",
        category: "breakfast",
      },
      // 午餐类
      {
        id: 2001,
        title: "清炒时蔬",
        imageUrl: "/images/discovers/png/qingjiaoshishu.png",
        description: "低脂健康的素食选择，富含膳食纤维",
        calories: 200,
        cookingTime: "20分钟",
        difficulty: "简单",
        category: "lunch",
      },
      {
        id: 2002,
        title: "香煎三文鱼",
        imageUrl: "/images/discovers/png/sanwenyu.png",
        description: "富含Omega-3脂肪酸的三文鱼，搭配时令蔬菜",
        calories: 450,
        cookingTime: "25分钟",
        difficulty: "中等",
        category: "lunch",
      },
      {
        id: 2003,
        title: "鸡胸肉沙拉",
        imageUrl: "/images/discovers/png/jixongrou.png",
        description: "高蛋白低脂的午餐选择，适合减脂期",
        calories: 380,
        cookingTime: "20分钟",
        difficulty: "简单",
        category: "lunch",
      },
      {
        id: 2004,
        title: "藜麦牛肉饭",
        imageUrl: "/images/discovers/png/niujroufan.png",
        description: "藜麦搭配牛肉，营养全面",
        calories: 520,
        cookingTime: "30分钟",
        difficulty: "中等",
        category: "lunch",
      },
      // 晚餐类
      {
        id: 3001,
        title: "养生排骨汤",
        imageUrl: "/images/discovers/png/paigutang.png",
        description: "滋补养生的排骨汤，营养丰富",
        calories: 450,
        cookingTime: "60分钟",
        difficulty: "中等",
        category: "dinner",
      },
      {
        id: 3002,
        title: "清蒸鲈鱼",
        imageUrl: "/images/discovers/png/qingzhengluyu.png",
        description: "清淡可口的清蒸鲈鱼，富含优质蛋白质",
        calories: 380,
        cookingTime: "30分钟",
        difficulty: "中等",
        category: "dinner",
      },
      {
        id: 3003,
        title: "低脂意面",
        imageUrl: "/images/discovers/png/yidalimina.png",
        description: "健康低脂的意大利面，晚餐良选",
        calories: 420,
        cookingTime: "25分钟",
        difficulty: "简单",
        category: "dinner",
      },
      {
        id: 3004,
        title: "烤鸡胸配时蔬",
        imageUrl: "/images/discovers/png/kaojixiong.png",
        description: "低脂高蛋白的晚餐，控制热量摄入",
        calories: 380,
        cookingTime: "35分钟",
        difficulty: "中等",
        category: "dinner",
      },
      // 小食类
      {
        id: 4001,
        title: "水果沙拉",
        imageUrl: "/images/discovers/png/shuiguoshala.png",
        description: "多种新鲜水果搭配，补充维生素",
        calories: 150,
        cookingTime: "10分钟",
        difficulty: "简单",
        category: "snack",
      },
      {
        id: 4002,
        title: "坚果能量棒",
        imageUrl: "/images/discovers/png/nengliangbang.png",
        description: "富含健康脂肪和蛋白质的能量零食",
        calories: 200,
        cookingTime: "15分钟",
        difficulty: "简单",
        category: "snack",
      },
      {
        id: 4003,
        title: "草莓酸奶杯",
        imageUrl: "/images/discovers/png/caomeisuannai.png",
        description: "美味健康的草莓酸奶，营养丰富",
        calories: 180,
        cookingTime: "5分钟",
        difficulty: "简单",
        category: "snack",
      },
      {
        id: 4004,
        title: "蔬菜低脂饼干",
        imageUrl: "/images/discovers/png/binggan.png",
        description: "添加蔬菜的低脂饼干，营养健康",
        calories: 160,
        cookingTime: "25分钟",
        difficulty: "中等",
        category: "snack",
      },
      // 汤品类
      {
        id: 5001,
        title: "番茄蛋花汤",
        imageUrl: "/images/discovers/png/fanqiedanhua.png",
        description: "酸甜可口的番茄蛋花汤，开胃又营养",
        calories: 180,
        cookingTime: "15分钟",
        difficulty: "简单",
        category: "soup",
      },
      {
        id: 5002,
        title: "玉米排骨汤",
        imageUrl: "/images/discovers/png/yumipaigu.png",
        description: "香甜的玉米搭配排骨，营养美味",
        calories: 320,
        cookingTime: "45分钟",
        difficulty: "中等",
        category: "soup",
      },
      {
        id: 5003,
        title: "冬瓜海带汤",
        imageUrl: "/images/discovers/png/dongguahaidai.png",
        description: "清淡可口的冬瓜海带汤，低卡路里",
        calories: 120,
        cookingTime: "30分钟",
        difficulty: "简单",
        category: "soup",
      },
      {
        id: 5004,
        title: "鸡汤豆腐羹",
        imageUrl: "/images/discovers/png/jitangdoufugeng.png",
        description: "滋补养生的鸡汤豆腐羹，温暖又营养",
        calories: 280,
        cookingTime: "40分钟",
        difficulty: "中等",
        category: "soup",
      },
      // 素食类
      {
        id: 6001,
        title: "清炒西兰花",
        imageUrl: "/images/discovers/png/xilanhua.png",
        description: "富含维生素C的西兰花，简单又健康",
        calories: 120,
        cookingTime: "15分钟",
        difficulty: "简单",
        category: "vegetable",
      },
      {
        id: 6002,
        title: "素炒豆腐",
        imageUrl: "/images/discovers/png/doufu.png",
        description: "富含植物蛋白的豆腐，营养丰富",
        calories: 250,
        cookingTime: "20分钟",
        difficulty: "简单",
        category: "vegetable",
      },
      {
        id: 6003,
        title: "蔬菜沙拉配芝麻酱",
        imageUrl: "/images/discovers/png/shalapeizhimajiang.png",
        description: "多种蔬菜搭配芝麻酱，美味营养",
        calories: 220,
        cookingTime: "15分钟",
        difficulty: "简单",
        category: "vegetable",
      },
      {
        id: 6004,
        title: "香菇青菜",
        imageUrl: "/images/discovers/png/xiangguqingcai.png",
        description: "香菇搭配青菜，鲜美可口",
        calories: 180,
        cookingTime: "20分钟",
        difficulty: "简单",
        category: "vegetable",
      },
    ];
  },

  // 切换分类
  changeCategory: function (e) {
    const category = e.currentTarget.dataset.category;
    console.log("切换分类:", category); // 添加日志

    // 如果是切换到全部分类，同时清空搜索状态
    if (category === "") {
      this.setData(
        {
          selectedCategory: category,
          page: 1,
          hasMore: true,
          recipeList: [],
          searchKeyword: "",
          showSearchResult: false,
          isSearching: false,
        },
        () => {
          this.getRecipeList();
        }
      );
    } else {
      // 其他分类的切换逻辑保持不变
      this.setData(
        {
          selectedCategory: category,
          page: 1,
          hasMore: true,
          recipeList: [],
        },
        () => {
          // 如果当前是在搜索状态，则调用搜索API
          if (this.data.showSearchResult) {
            this.searchRecipes();
          } else {
            this.getRecipeList();
          }
        }
      );
    }
  },

  // 查看菜谱详情
  viewRecipeDetail: function (e) {
    const recipeId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/recipe/detail/index?id=${recipeId}`,
    });
  },

  // 显示/隐藏筛选
  toggleFilter: function () {
    this.setData({
      showFilter: !this.data.showFilter,
    });
  },

  // 获取搜索历史
  getSearchHistory() {
    const history = wx.getStorageSync("recipeSearchHistory") || [];
    this.setData({ searchHistory: history });
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    let history = wx.getStorageSync("recipeSearchHistory") || [];
    // 删除已存在的相同关键词
    history = history.filter((item) => item !== keyword);
    // 将新关键词添加到开头
    history.unshift(keyword);
    // 只保留最近10条记录
    history = history.slice(0, 10);
    wx.setStorageSync("recipeSearchHistory", history);
    this.setData({ searchHistory: history });
  },

  // 清空搜索历史
  clearSearchHistory() {
    wx.showModal({
      title: "提示",
      content: "确定要清空搜索历史吗？",
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync("recipeSearchHistory");
          this.setData({ searchHistory: [] });
        }
      },
    });
  },

  // 输入搜索关键词
  onSearchInput(e) {
    const keyword = e.detail.value.trim();
    this.setData({
      searchKeyword: keyword,
    });
    
    // 实时搜索，使用防抖减少请求次数
    if (keyword && keyword.length >= 2) {
      this.debounce(() => {
        this.setData({
          showSearchResult: true,
          page: 1,
          hasMore: true,
          recipeList: [],
        }, () => {
          this.searchRecipes();
        });
      }, 500);
    } else if (!keyword) {
      this.setData({
        showSearchResult: false,
      });
    }
  },

  // 搜索框获取焦点
  onSearchFocus() {
    this.setData({
      isSearching: true,
    });
  },

  // 搜索框失去焦点
  onSearchBlur() {
    // 如果没有进行搜索且没有关键词，则退出搜索状态
    if (!this.data.showSearchResult && !this.data.searchKeyword) {
      this.setData({
        isSearching: false,
      });
    }
  },

  // 确认搜索
  onSearchConfirm(e) {
    const keyword = e.detail.value.trim();
    if (keyword) {
      // 首先检查缓存中是否有结果
      const cacheKey = `${keyword}_${this.data.selectedCategory}`;
      if (this.data.searchResultCache[cacheKey]) {
        console.log("使用缓存的搜索结果:", cacheKey);
        this.setData({
          searchKeyword: keyword,
          showSearchResult: true,
          isSearching: true,
          page: 1,
          recipeList: this.data.searchResultCache[cacheKey].list,
          hasMore: this.data.searchResultCache[cacheKey].hasMore,
        });
        this.saveSearchHistory(keyword);
      } else {
        this.setData(
          {
            searchKeyword: keyword,
            showSearchResult: true,
            isSearching: true,
            page: 1,
            hasMore: true,
            recipeList: [],
          },
          () => {
            this.saveSearchHistory(keyword);
            this.searchRecipes();
          }
        );
      }
    }
  },

  // 取消搜索
  cancelSearch() {
    this.setData(
      {
        searchKeyword: "",
        showSearchResult: false,
        isSearching: false,
        page: 1,
        hasMore: true,
      },
      () => {
        // 退出搜索状态后，重新加载菜谱列表
        this.getRecipeList();
      }
    );
    
    // 清除搜索防抖定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
  },

  // 点击搜索历史
  onHistoryTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    
    // 首先检查缓存中是否有结果
    const cacheKey = `${keyword}_${this.data.selectedCategory}`;
    if (this.data.searchResultCache[cacheKey]) {
      console.log("使用缓存的搜索结果:", cacheKey);
      this.setData({
        searchKeyword: keyword,
        showSearchResult: true,
        isSearching: true,
        page: 1,
        recipeList: this.data.searchResultCache[cacheKey].list,
        hasMore: this.data.searchResultCache[cacheKey].hasMore,
      });
    } else {
      this.setData(
        {
          searchKeyword: keyword,
          showSearchResult: true,
          isSearching: true,
          page: 1,
          hasMore: true,
          recipeList: [],
        },
        () => {
          this.searchRecipes();
        }
      );
    }
  },

  // 搜索菜谱
  searchRecipes(isLoadMore = false) {
    if (this.data.loading || (!isLoadMore && !this.data.hasMore)) {
      return;
    }

    // 构建缓存 key
    const cacheKey = `${this.data.searchKeyword}_${this.data.selectedCategory}`;
    
    // 如果是加载更多并且缓存中存在结果，直接使用缓存结果
    if (isLoadMore && this.data.searchResultCache[cacheKey] && 
        this.data.searchResultCache[cacheKey].page >= this.data.page + 1) {
      const cachedResult = this.data.searchResultCache[cacheKey];
      this.setData({
        recipeList: [...this.data.recipeList, ...cachedResult.list],
        page: this.data.page + 1,
        hasMore: cachedResult.hasMore
      });
      return;
    }

    this.setData({
      loading: true,
      isSearching: true,
      showSearchResult: true, // 确保设置为true
    });

    const page = isLoadMore ? this.data.page + 1 : 1;

    // 调用搜索API
    api
      .searchRecipes({
        keyword: this.data.searchKeyword,
        category: this.data.selectedCategory,
        page: page,
        pageSize: this.data.pageSize,
      })
      .then((res) => {
        if (res.code === 200 && res.data) {
          const list = res.data.list || [];
          const total = res.data.total || 0;
          const hasMore = this.data.pageSize * page < total;

          // 修正API返回数据中的图片路径
          const correctedList = list.map((item) => {
            // 如果是/images/recipes/路径，改为/images/discovers/png/
            if (
              item.imageUrl &&
              item.imageUrl.includes("/images/recipes/")
            ) {
              // 获取文件名（不含后缀）
              const fileName = item.imageUrl.split("/").pop().split(".")[0];

              // 根据搜索词或菜谱内容选择合适的图片
              let newImageName = "";
              if (
                item.title.includes("三明治") ||
                fileName.includes("sandwich") ||
                fileName.includes("healthy")
              ) {
                newImageName = "sanmingzhi.png";
              } else if (
                item.title.includes("蔬菜") ||
                item.title.includes("时蔬")
              ) {
                newImageName = "qingjiaoshishu.png";
              } else if (
                item.title.includes("排骨") ||
                item.title.includes("汤")
              ) {
                newImageName = "paigutang.png";
              } else if (item.title.includes("水果")) {
                newImageName = "shuiguoshala.png";
              } else if (
                item.title.includes("能量") ||
                item.title.includes("营养")
              ) {
                newImageName = "nengliangbang.png";
              } else {
                // 默认图片
                newImageName = "sanmingzhi.png";
              }

              return {
                ...item,
                imageUrl: `/images/discovers/png/${newImageName}`,
              };
            }
            return item;
          });

          // 更新搜索结果缓存
          const searchResultCache = { ...this.data.searchResultCache };
          searchResultCache[cacheKey] = {
            list: correctedList,
            page: page,
            hasMore: hasMore,
            timestamp: Date.now()
          };
          
          this.setData({
            recipeList: isLoadMore
              ? [...this.data.recipeList, ...correctedList]
              : correctedList,
            page: page,
            hasMore: hasMore,
            showSearchResult: true,
            searchResultCache
          });
        }
      })
      .catch((err) => {
        console.error("搜索菜谱失败:", err);
        // 使用模拟数据
        let imageUrl = "/images/discovers/png/sanmingzhi.png";
        const keyword = this.data.searchKeyword;
        
        // 根据搜索关键词选择合适的图片
        if (keyword.includes("三明治") || keyword.includes("面包")) {
          imageUrl = "/images/discovers/png/sanmingzhi.png";
        } else if (keyword.includes("蔬菜") || keyword.includes("青菜") || keyword.includes("素食")) {
          imageUrl = "/images/discovers/png/qingjiaoshishu.png";
        } else if (keyword.includes("汤") || keyword.includes("排骨")) {
          imageUrl = "/images/discovers/png/paigutang.png";
        } else if (keyword.includes("水果") || keyword.includes("沙拉")) {
          imageUrl = "/images/discovers/png/shuiguoshala.png";
        } else if (keyword.includes("能量") || keyword.includes("营养")) {
          imageUrl = "/images/discovers/png/nengliangbang.png";
        } else if (keyword.includes("鱼") || keyword.includes("海鲜")) {
          imageUrl = "/images/discovers/png/qingzhengluyu.png";
        } else if (keyword.includes("饼干")) {
          imageUrl = "/images/discovers/png/binggan.png";
        } else if (keyword.includes("意面") || keyword.includes("意大利")) {
          imageUrl = "/images/discovers/png/yidalimina.png";
        }
        
        const mockList = [
          {
            id: 1,
            title: "健康" + this.data.searchKeyword + "食谱",
            imageUrl: imageUrl,
            description:
              "这是一道健康美味的" + this.data.searchKeyword + "菜品",
            calories: 300,
            cookingTime: "30分钟",
            difficulty: "简单",
            category: "健康菜",
          },
        ];

        this.setData({
          recipeList: isLoadMore
            ? [...this.data.recipeList, ...mockList]
            : mockList,
          page: page,
          hasMore: false,
          showSearchResult: true, // 确保设置为true
        });
      })
      .finally(() => {
        this.setData({
          loading: false,
          showSearchResult: true, // 最后再确保为true
        });
        wx.stopPullDownRefresh();
      });
  },

  // 重写上拉加载更多
  onReachBottom: function () {
    if (this.data.hasMore && !this.data.loading) {
      if (this.data.showSearchResult) {
        this.searchRecipes(true);
      } else {
        this.getRecipeList(true);
      }
    }
  },
  
  // 清理过期缓存
  clearExpiredCache() {
    const now = Date.now();
    const searchResultCache = { ...this.data.searchResultCache };
    let hasExpired = false;
    
    // 清除超过10分钟的缓存
    Object.keys(searchResultCache).forEach(key => {
      if (now - searchResultCache[key].timestamp > 10 * 60 * 1000) {
        delete searchResultCache[key];
        hasExpired = true;
      }
    });
    
    if (hasExpired) {
      this.setData({ searchResultCache });
    }
  }
});
